#!/usr/bin/env python
# -*- coding: utf-8 -*-
# author:Charles.chen
# createDate:2017/9/5
# Title:
# Tip:
from app.model import Dust, SensorData, Sensor
from app.toolkit.decoratorUtil import catchDbException
from app.toolkit import commonUtil

# 根据微尘命令 获得微尘列表
def getDustTableByZigBee():
    data = [{
        "id": "1",
        "type": "A1",
        "power": "X1"
    }, {
        "id": "2",
        "type": "A2",
        "power": "X2"
    }, {
        "id": "3",
        "type": "A3",
        "power": "X3"
    }, {
        "id": "4",
        "type": "A4",
        "power": "X4"
    }, {
        "id": "5",
        "type": "A5",
        "power": "X5"
    }]
    # 从现在数据库中进行筛选  如果微尘已在数据库中记录 status=True,反之 statsu=False
    existDust = getAllDust(is_used=True)
    existDustIds = []
    existDict = {}
    if existDust:
        for item in existDust:
            existDustIds.append(item["unique_id"])
            existDict[item["unique_id"]] = item
        for item in data:
            if item['id'] in existDustIds:
                if existDict[item["id"]]["is_used"] is True:
                    item["status"] = True
                else:
                    item["status"] = False
            else:
                item["status"] = False
            pass
    response = {
        "data": data,
        "draw": 1,
        "recordsTotal": len(data),
        "recordsFiltered": len(data),
    }


    return response
    pass


# 获取微尘列表
# type 类型0:失效 1：运行 默认1 获取运行中的微尘
def getDustList(type=True):
    try:
        res = Dust.select(Dust.is_used == Type).where().execute()
    except Exception:
        res = None
    return res

# 设置微尘的配置信息
# 通过命令的方式
def setDustConfig(configNo=None):


    pass

# 获取微尘详情
def getDustInfo(dust_id=None):
    res = Dust.select().where(Dust.id == dust_id).execute()
    return res

# 根据微尘唯一id获取内置信息
def getDustInfoByCommand(uniqueId=None):

    pass

# 在数据库中添加管控的微尘数据
def addDust(data=None):
    insert_dict = {
        "unique_id": data["id"],
        "interface_name": data["type"],
        "power_type": data["power"]
    }
    return Dust.insert(insert_dict).execute()
    pass

# 在数据库中添加管控的微尘数据 批量插入存在状态问题 需要根据每一个状态进行处理
@catchDbException
def addDustMulti(data=[]):
    existDust = getAllDust()
    existIds = []
    existDict = {}
    for item in existDust:
        existIds.append(item["unique_id"])
        existDict[item["unique_id"]] = item
        pass
    # 对传来数据进行区分 新数据 旧数据
    insertArray = []
    connectArray = []
    disconnectArray = []

    for item in data:
        if item["id"] in existIds:
            existItem = existDict[item["id"]]
            if existItem["is_used"] is True:
                disconnectArray.append(item["id"])
                pass
            else:
                connectArray.append(item["id"])
                pass
            pass
        else:
            insert_dict = {
                "unique_id": item["id"],
                "interface_name": item["type"],
                "power_type": item["power"]
            }
            insertArray.append(insert_dict)
            pass
    #     最后处理结果
    if insertArray and len(insertArray) > 0:
        Dust.insert_many(insertArray).execute()
        pass
    if connectArray and len(connectArray) > 0:
        updateDustUsed(connectArray, True)
        pass
    if disconnectArray and len(disconnectArray) > 0:
        updateDustUsed(disconnectArray, False)
        pass

    return True

# 修改微尘所使用的配置文件
def updateConfigIdForDust(duct_id=None, config_id=None, config_name=None):
    return Dust.update(Dust.config_id == config_id and Dust.config_name == config_name).where(Dust.id == duct_id).execute()

# 获取所有的微尘数据
# return [] or dict
# is_used: none：所有 || True 所有有效的 || False：所有无效的
def getAllDust(is_used=None):
    res = getAll(is_used)
    if res is None:
        return []
    else:
        data = commonUtil.convertDbObjToDict(res, Dust)
        return data

# 修改微尘的使用状态
def updateDustUsed(uniqueIds=None,is_used=True):
    return Dust.update(is_used=is_used).where(Dust.unique_id << uniqueIds).execute()

    pass

# 获取微尘下的传感器列表
def getSensorList(dust_id=None):
    return Dust.select().join(Sensor, on=(Dust.unique_id == Sensor.sensor_no)).where(Dust.id == dust_id).execute()

@catchDbException
def getAll(is_used=None):
    if is_used is None:
        return Dust.select().execute()
    else:
        return Dust.select().where(Dust.is_used==is_used).execute()



if __name__ == '__main__':
    pass